import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux, Link } from 'dva/router';
import { Form, Input, Button, Icon, Alert } from 'antd';
import styles from './Login.less';
const FormItem = Form.Item;

@connect(({ login }) => ({
  login,
}))
@Form.create()
export default class Login extends Component {
  state = {
    count: 0,
    codeData: {},
    type: 'userName',
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'login/fetchCode',
      callback: () => {
        const { login: { codeData } } = this.props
        this.setState({
          codeData: codeData
        })
      }
    });
  }

  componentWillReceiveProps(nextProps) {
    //if (nextProps.login.message === '登录成功') {
    const oldStatus = this.props.login.status;
    const newStatus = nextProps.login.status;

    if (oldStatus !== 'ok' && newStatus === 'ok') {
      this.props.dispatch(routerRedux.push('/'));
      //alert("hello");
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  onSwitch = (key) => {
    this.setState({
      type: key,
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields({ force: true },
      (err, values) => {
        if (!err) {
          sessionStorage.setItem("password", values.password)
          sessionStorage.setItem("userName", values.userName)
          this.props.dispatch({
            type: `login/accountSubmit`,
            payload: {
              password: values.password,
              userName: values.userName,
              yzm: values.code,
              key: this.state.codeData.key,
            },
            callback: () =>{
              // this.props.dispatch({
              //   type: 'global/fetchNotices',
              // });
            }
          });
        }
      }
    );
  }

  handleRefreshCode = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'login/fetchCode',
      callback: () => {
        const { login: { codeData } } = this.props
        this.setState({
          codeData: codeData
        })
      }
    });
  }

  renderMessage = (message) => {
    return (
      <Alert
        style={{ marginBottom: 24 }}
        message={message}
        type="error"
        showIcon
      />
    );
  }

  render() {
    const { form, login } = this.props;
    const { getFieldDecorator } = form;
    const { count, type } = this.state;

    const hasError = login.loginResult.result.success === false;
    const message = login.loginResult.result.message;
    const isLoading = login.submitting === true;

    // console.log("isLoading",isLoading);
    return (
      <div className={styles.main}>
        <Form onSubmit={this.handleSubmit}>

          {/* {JSON.stringify(login.loginResult)}
        { JSON.stringify(login.submitting)} */}

            {
              hasError &&
              login.submitting === false &&
              this.renderMessage(message)
            }
          {/* <FormItem>
            {getFieldDecorator('enterpriseNumber', {
              rules: [{
                required: true, message: '请输入企业号！',
              }],
            })(
              <Input
                size="large"
                prefix={<Icon type="bank" className={styles.prefixIcon} />}
                placeholder="请输入您的企业号"
              />
            )}
          </FormItem> */}
          <FormItem>
            {getFieldDecorator('userName', {
              rules: [{
                required: true, message: '请输入账户名！',
              }],
            })(
              <Input
                size="large"
                prefix={<Icon type="user" className={styles.prefixIcon} />}
                placeholder="请输入您的账号"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('password', {
              rules: [{
                required: true, message: '请输入密码！',
              }],
            })(
              <Input
                size="large"
                prefix={<Icon type="lock" className={styles.prefixIcon} />}
                type="password"
                placeholder="请输入您的密码"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('code', {
              rules: [{
                required: true, message: '请输入验证码！',
              }],
            })(
              <div>
                <Input
                  size="large"
                  style={{ width: '50%' }}
                  prefix={<Icon type="safety" className={styles.prefixIcon} />}
                  placeholder="请输入验证码"
                />
                <img
                  src={this.state.codeData.yzm}
                  size="large"
                  style={{ width: '30%', height: 35, marginLeft: 20, marginBottom: 3 }}
                />
                <Button shape="circle" icon="reload" style={{ marginLeft: 20 }} onClick={this.handleRefreshCode} />
              </div>
            )}
          </FormItem>
          <FormItem className={styles.additional}>
            <Button size="large" loading={login.submitting} className={styles.submit} type="primary" htmlType="submit">
              登录
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}
